// API服务配置
const API_BASE_URL = 'http://127.0.0.1:8080/api';

// 请求拦截器
const request = (url, options = {}) => {
  const token = uni.getStorageSync('token');
  
  console.log('API请求:', {
    url: `${API_BASE_URL}${url}`,
    method: options.method || 'GET',
    hasToken: !!token,
    tokenPreview: token ? token.substring(0, 20) + '...' : 'null'
  });
  
  const defaultOptions = {
    url: `${API_BASE_URL}${url}`,
    header: {
      'Content-Type': 'application/json',
      ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
      ...options.header
    },
    ...options
  };

  return new Promise((resolve, reject) => {
    uni.request({
      ...defaultOptions,
      success: (res) => {
        console.log('API响应:', {
          url: `${API_BASE_URL}${url}`,
          statusCode: res.statusCode,
          data: res.data
        });
        
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        } else if (res.statusCode === 401) {
          // token过期，跳转登录
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
          reject(new Error('登录已过期'));
        } else {
          const errorMsg = res.data && res.data.message ? res.data.message : '请求失败';
          reject(new Error(`HTTP ${res.statusCode}: ${errorMsg}`));
        }
      },
      fail: (err) => {
        console.error('API请求失败:', err);
        reject(new Error(err.errMsg || '网络请求失败'));
      }
    });
  });
};

// 用户相关API
export const userAPI = {
  // 用户注册
  register: (data) => request('/auth/register', {
    method: 'POST',
    data
  }),

  // 用户登录
  login: (data) => request('/auth/login', {
    method: 'POST',
    data
  }),

  // 刷新token
  refreshToken: () => request('/auth/refresh', {
    method: 'POST'
  }),

  // 退出登录
  logout: () => request('/auth/logout', {
    method: 'POST'
  }),

  // 获取用户信息
  getProfile: () => request('/users/profile'),

  // 更新用户信息
  updateProfile: (data) => request('/users/profile', {
    method: 'PUT',
    data
  }),

  // 更新用户详细信息
  updateDetailedProfile: (data) => request('/users/profile/detailed', {
    method: 'PUT',
    data
  }),

  // 修改密码
  changePassword: (data) => request('/users/password', {
    method: 'PUT',
    data
  }),

  // 检查用户名是否存在
  checkUsername: (username) => request(`/users/check-username?username=${username}`),

  // 检查邮箱是否存在
  checkEmail: (email) => request(`/users/check-email?email=${email}`)
};

// 文件上传相关API
export const fileAPI = {
  // 上传头像
  uploadAvatar: (filePath) => {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token');
      
      uni.uploadFile({
        url: `${API_BASE_URL}/file/upload/avatar`,
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.code === 200) {
              resolve(data.data);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (e) {
            reject(new Error('响应解析失败'));
          }
        },
        fail: (err) => {
          reject(new Error(err.errMsg || '上传失败'));
        }
      });
    });
  },

  // 删除头像
  deleteAvatar: (fileName) => request(`/file/delete/avatar/${fileName}`, {
    method: 'DELETE'
  })
};

// 分类相关API
export const categoryAPI = {
  // 获取所有分类
  getAll: () => request('/categories'),

  // 根据类型获取分类
  getByType: (type) => request(`/categories/type/${type}`),

  // 获取分类详情
  getById: (id) => request(`/categories/${id}`),

  // 添加分类
  add: (data) => request('/categories', {
    method: 'POST',
    data
  }),

  // 更新分类
  update: (id, data) => request(`/categories/${id}`, {
    method: 'PUT',
    data
  }),

  // 删除分类
  delete: (id) => request(`/categories/${id}`, {
    method: 'DELETE'
  }),

  // 启用/禁用分类
  toggle: (id) => request(`/categories/${id}/toggle`, {
    method: 'PUT'
  })
};

// 记录相关API
export const recordAPI = {
  // 添加记录
  add: (data) => request('/records', {
    method: 'POST',
    data
  }),

  // 更新记录
  update: (id, data) => request(`/records/${id}`, {
    method: 'PUT',
    data
  }),

  // 删除记录
  delete: (id) => request(`/records/${id}`, {
    method: 'DELETE'
  }),

  // 获取记录详情
  getById: (id) => request(`/records/${id}`),

  // 获取用户所有记录
  getAll: () => request('/records'),

  // 根据类型获取记录
  getByType: (type) => request(`/records/type/${type}`),

  // 根据日期范围获取记录
  getByDateRange: (startDate, endDate) => request(`/records/date-range?startDate=${startDate}&endDate=${endDate}`),

  // 根据类型和日期范围获取记录
  getByTypeAndDateRange: (type, startDate, endDate) => request(`/records/type/${type}/date-range?startDate=${startDate}&endDate=${endDate}`),

  // 获取统计数据
  getStatistics: (startDate, endDate) => request(`/records/statistics?startDate=${startDate}&endDate=${endDate}`),

  // 获取概览数据
  getOverview: (startDate, endDate) => request(`/records/statistics/overview?startDate=${startDate}&endDate=${endDate}`),

  // 获取趋势数据
  getTrend: (startDate, endDate) => request(`/records/statistics/trend?startDate=${startDate}&endDate=${endDate}`),

  // 获取分类统计
  getCategoryStats: (type, startDate, endDate) => request(`/records/statistics/category?recordType=${type}&startDate=${startDate}&endDate=${endDate}`),

  // 获取排行榜
  getRanking: (type, startDate, endDate) => request(`/records/statistics/ranking?recordType=${type}&startDate=${startDate}&endDate=${endDate}`)
};

// 账户相关API
export const accountAPI = {
  // 获取用户所有启用的账户
  getAccounts: () => request('/accounts'),

  // 获取用户所有账户（包括禁用的）
  getAllAccounts: () => request('/accounts/all'),

  // 根据ID获取账户
  getById: (id) => request(`/accounts/${id}`),

  // 创建账户
  create: (data) => request('/accounts', {
    method: 'POST',
    data
  }),

  // 更新账户
  update: (id, data) => request(`/accounts/${id}`, {
    method: 'PUT',
    data
  }),

  // 删除账户
  delete: (id) => request(`/accounts/${id}`, {
    method: 'DELETE'
  }),

  // 启用/禁用账户
  toggle: (id) => request(`/accounts/${id}/toggle`, {
    method: 'PUT'
  }),

  // 获取用户总资产
  getTotalBalance: () => request('/accounts/total-balance'),

  // 初始化默认账户
  initialize: () => request('/accounts/initialize', {
    method: 'POST'
  }),

  // 获取账户历史记录
  getAccountRecords: (accountId) => request(`/records/account/${accountId}`),

  // 根据日期范围获取账户历史记录
  getAccountRecordsByDateRange: (accountId, startDate, endDate) => 
    request(`/records/account/${accountId}/date-range?startDate=${startDate}&endDate=${endDate}`)
};

// 工具函数
export const apiUtils = {
  // 设置token
  setToken: (token) => {
    uni.setStorageSync('token', token);
  },

  // 获取token
  getToken: () => {
    return uni.getStorageSync('token');
  },

  // 清除token
  clearToken: () => {
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
  },

  // 检查是否已登录
  isLoggedIn: () => {
    return !!uni.getStorageSync('token');
  }
};

export default {
  userAPI,
  categoryAPI,
  recordAPI,
  accountAPI,
  apiUtils
};

